package safeCommitter.utils;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.core.JavaElement;
import org.eclipse.jdt.internal.core.JavaProject;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeSelection;

import safeCommitter.model.adpters.ClassEntity;

public class JavaModelUtils {

	public static JavaProject getJavaProject(final ISelection selection) {
		TreeSelection sel = (TreeSelection) selection;
		Object element = sel.getFirstElement();
		if (element instanceof JavaElement)
			return (JavaProject) ((JavaElement) element).getJavaProject();
		return null;

	}

	public static ClassEntity getClassEntity(final ICompilationUnit unit) {
		ClassEntity clazz = new ClassEntity();
		clazz.setName(getClassName(unit));
		try {
			clazz.getMethods().addAll(getMethods(unit));
		} catch (JavaModelException e) {
			e.printStackTrace();
		}

		return clazz;
	}

	private static Collection<? extends IMethod> getMethods(final ICompilationUnit unit) throws JavaModelException {

		Set<IMethod> set = new HashSet<IMethod>();
		for (IType type : unit.getTypes()) {
			set.addAll(Arrays.asList(type.getMethods()));
		}
		return set;

	}

	public static String getClassName(final ICompilationUnit c) {
		String className = c.getElementName().split("\\.")[0];
		IPackageFragment parent = (IPackageFragment) c.getParent();
		String packageName = parent.getElementName();
		return packageName + "." + className;
	}

}
